package cn.kk.librarysystem.controller;

import cn.kk.librarysystem.mapper.StudentMapper;
import cn.kk.librarysystem.pojo.Student;
import cn.kk.librarysystem.service.StudentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;


/*
 *@author KK on 2022.10.14 20:18
 */
@Controller
@RequestMapping("/stu")
@Api(value = "学生控制层",tags = "控制层")
public class StudentController {
    @Autowired
    private StudentService studentService;
    @Autowired
    StudentMapper studentMapper;

    @ApiOperation("获取全部学生数据")
    @GetMapping("/getStudentList")
    public String getStudentList(HttpSession session, Model model){
        Student stu = (Student) session.getAttribute("is_login");
        if (stu!=null) {
            List<Student> stus = studentService.list();
            model.addAttribute("stus",stus);
            return "stuList";
        }else{
            return "login";
        }
    }

    @ApiOperation("登录")
    @RequestMapping("/login")
    public String login(String username, String password, HttpSession session){
        QueryWrapper qw = new QueryWrapper();
        qw.eq("name",username);
        qw.eq("password",password);
        Student student = studentMapper.selectOne(qw);
        String msg = "登录成功";
        if (student!=null) {
            session.setAttribute("msg",msg);
            session.setAttribute("is_login",student);
            return "msg";
        }else {
            return "login";
        }
    }
    @ApiOperation("注销")
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request){
        request.getSession().invalidate();
        return "login";
    }

    @ApiOperation("添加学生")
    @RequestMapping("/addStu")
    public String addStu(Student student,HttpSession session){
        int i = studentMapper.addStu(student);
        if (i>0){
            session.setAttribute("msg","添加成功");
            return "msg";
        }
        return "msg";
    }

    @ApiOperation("学生注册")
    @RequestMapping("/register")
    public String register(Student student,HttpSession session){
        int i = studentMapper.addStu(student);
        System.out.println(i);
        if (i>0){
            session.setAttribute("msg","添加成功");
            return "msg";
        }
        return "msg";
    }

    @ApiOperation("删除学生")
    @RequestMapping("/delStu")
    public String delStu(int id,HttpSession session){
        int i = studentMapper.deleteById(id);
        if (i>0) {
            session.setAttribute("msg","删除成功！");
        }
        return "msg";
    }
}
